package cn.dgiot.fd.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

import cn.dgiot.fd.contant.SysConfig;
import cn.dgiot.fd.model.FileModel;
import cn.dgiot.fd.service.IFileService;

/**
 * [文件上传]
 * @author
 */
@RequestMapping("/file")
@Controller
public class FileUploadController {
    
	private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);
	
	@Autowired
	private SysConfig sysConfig;
	
	@Autowired
	private IFileService fileService;


    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
    	Map<String,Object> resultMap = new HashMap<String,Object>();
        if (file.isEmpty()) {
        	resultMap.put("success", false);
        	resultMap.put("errorMessage", "上传失败，请选择文件");
            return JSON.toJSONString(resultMap);
        }
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String fileName = file.getOriginalFilename();
        String suffix = "";
        if(fileName.indexOf(".") > 0) {
        	suffix = fileName.substring(fileName.indexOf("."),fileName.length());
        }
        String filePath = sysConfig.uploadPath;
        File dest = new File(filePath + uuid+suffix);
        try {
            file.transferTo(dest);
            resultMap.put("success", true);
            resultMap.put("fileId", uuid);
            
            FileModel fileModel = new FileModel();
            fileModel.setFileId(uuid);
            fileModel.setFileName(uuid+suffix);
            fileModel.setOriginalFileName(fileName);
            fileService.insertFile(fileModel);
            LOGGER.info("上传成功");
        } catch (IOException e) {
        	resultMap.put("success", false);
        	resultMap.put("errorMessage", "上传失败，请选择文件");
            LOGGER.error(e.toString(), e);
        }
        return JSON.toJSONString(resultMap);
    }

}
